package com.yuki.consumer.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.baidu.aip.face.AipFace;
import com.yuki.api.annotation.LogType;
import com.yuki.api.annotation.SystemLog;
import com.yuki.api.annotation.UserLoginToken;
import com.yuki.api.common.AIFactoryUtil;
import com.yuki.api.common.CommonResult;
import com.yuki.api.dto.AIBaiduFaceBean;
import com.yuki.api.dto.AIFaceBean;
import com.yuki.api.dto.UmsAdminLoginParam;
import com.yuki.api.model.UmsAdmin;
import com.yuki.api.model.UmsLog;
import com.yuki.api.service.ITokenService;
import com.yuki.api.service.IUserService;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: Yuki Tadayoshi
 * @time: 2021/3/24 17:49
 */
@RestController
@RequestMapping("/admin")
@CrossOrigin
public class UmsUserController {
    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Reference(
            version = "1.0.0",
            interfaceName = "com.yuki.api.service.IUserService",
            interfaceClass = IUserService.class,
            timeout = 120000
    )
    private IUserService service;

    @Reference(
            version = "1.0.0",
            interfaceName = "com.yuki.api.service.ITokenService",
            interfaceClass = ITokenService.class,
            timeout = 120000
    )
    private ITokenService tokenService;

    private AipFace aipFace = AIFactoryUtil.getAipFace();

    @PostMapping(value = "/login")
    @ResponseBody
    public CommonResult login(@RequestBody UmsAdminLoginParam user) {
        UmsAdmin user1 = null;
        user1 = service.findByUsername(user.getUsername());
        if (user1 == null)
            return CommonResult.validateFailed("用户不存在！");
        else {
            if (!user1.getPassword().equals(user.getPassword())) {
                Map<String, String> map = new HashMap<>();
                map.put("error_code", "500");
                return CommonResult.failed(map);
            } else {
                String token = tokenService.getToken(user1.getId().toString(), user1.getPassword());
                Map<String, String> map = new HashMap<>();
                map.put("token", token);
                map.put("error_code", "200");
                map.put("tokenHead", tokenHead);
                return CommonResult.success(map);
            }
        }
    }

    @PostMapping(value = "/flogin")
    @ResponseBody
    public CommonResult faceLogin(@RequestBody AIFaceBean faceBean) {
        Map<String, String> tokenMap = new HashMap<>();
        String groupId = "login";
        JSONObject resultObject = aipFace.search(faceBean.getImgdata(), "BASE64", groupId, null);
        //使用fastJson处理数据
        AIBaiduFaceBean faceSearchResponse = JSON.parseObject(resultObject.toString(), AIBaiduFaceBean.class);
        if (faceSearchResponse.getError_code().equals("0") && faceSearchResponse.getError_msg().equals("SUCCESS")) {
            if (faceSearchResponse.getResult().getUser_list().get(0).getScore() > 80) {
                faceBean.setError_code(faceSearchResponse.getError_code());
                faceBean.setError_msg(faceSearchResponse.getError_msg());
                String userId = faceSearchResponse.getResult().getUser_list().get(0).getUser_id();
                UmsAdmin admin = service.findUserById(Long.parseLong(userId));
                String username = admin.getUsername();
                String password = admin.getPassword();
                String token = tokenService.getToken(userId, password);
                tokenMap.put("error_code", faceBean.getError_code());
                tokenMap.put("token", token);
                tokenMap.put("tokenHead", tokenHead);
                tokenMap.put("username", username);
                tokenMap.put("password", password);
                return CommonResult.success(tokenMap);
            } else {
                tokenMap.put("error_code", faceSearchResponse.getError_code());
                return CommonResult.failed(tokenMap);
            }
        } else {
            tokenMap.put("error_code", faceSearchResponse.getError_code());
            return CommonResult.failed(tokenMap);
        }
    }

    @GetMapping("/info")
    @ResponseBody
    @UserLoginToken
    @SystemLog(description = "获取当前登录用户信息", type = LogType.USER_INFO)
    public CommonResult getAdminInfo(HttpServletRequest request) {
        String token = request.getHeader(tokenHeader);
        String tokenStr = token.split("@")[1];
        UmsAdmin admin = service.findByUmsAdmin(tokenStr);
        Map<String, Object> data = new HashMap<>();
        data.put("username", admin.getUsername());
        data.put("roles", new String[]{"TEST"});
        data.put("icon", admin.getIcon());
        return CommonResult.success(data);
    }


    @PostMapping(value = "/logout")
    @ResponseBody
    @SystemLog(description = "登出",type = LogType.USER_LOGIN_OUT)
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @PostMapping(value = "/reg")
    @ResponseBody
    public CommonResult reg(@RequestBody UmsAdmin umsAdmin) {
        if (service.findByUsername(umsAdmin.getUsername()) != null) {
            Map<String, String> tokenMap = new HashMap<>();
            tokenMap.put("error_code", "500");
            return CommonResult.failed(tokenMap);
        }
        HashMap<String, String> options = new HashMap<>();
        options.put("userInfo", umsAdmin.getPassword());
        UmsAdmin a = service.reg(umsAdmin);
        //百度人脸注册
        String b64 = umsAdmin.getPic().substring(22);
        JSONObject result = aipFace.addUser(
                b64,
                "BASE64", "login", a.getId().toString(), options
        );
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("error_code", "200");
        return CommonResult.success(tokenMap);
    }
}
